package com.user.controller;

import com.common.VO.SysResult;
import com.common.domain.User;
import com.common.utils.CookieUtils;
import com.user.exception.MsgException;
import com.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

/**
 * @author Elias
 * @version 1.0
 * @date 2021-06-04 9:28
 * @description
 * @copyright 2021
 */
@RestController
@RequestMapping("/user")
public class UserController {
  @Autowired private UserService userService;

  /**
   * 检查用户名是否可用
   *
   * @param username 用户名
   * @return
   */
  @GetMapping("/manage/checkUsername")
  @ResponseBody
  public SysResult checkUsername(@RequestParam("username") String username) {
    try {
      boolean available = userService.checkUserName(username);
      if (!available) {
        return SysResult.build(201, "用户名已存在", null);
      }
      return SysResult.build(200, "用户名可用", null);
    } catch (Exception e) {
      return SysResult.build(500, e.getMessage(), e);
    }
  }

  /**
   * 用户注册
   *
   * @param user 用户
   * @param userPassword2 确认密码
   * @param valistr 验证码
   * @param token 验证码key
   * @param errors 校验错误
   * @return
   */
  @PostMapping("/manage/save")
  @ResponseBody
  public SysResult registerUser(
      @Valid User user,
      @RequestParam("userPassword2") String userPassword2,
      @RequestParam("valistr") String valistr,
      @RequestParam("token") String token,
      Errors errors) {
    try {
      userService.registerUser(user, errors, userPassword2, valistr, token);
      return SysResult.build(200, "ok", null);
    } catch (Exception e) {
      return SysResult.build(500, e.getMessage(), e);
    }
  }

  /**
   * 用户登录
   *
   * @param user
   * @param valistr
   * @param token
   * @param remname
   * @param autologin
   * @param request
   * @param response
   * @return
   */
  @PostMapping("/manage/login")
  @ResponseBody
  public SysResult loginUser(
      User user,
      @RequestParam("valistr") String valistr,
      @RequestParam("token") String token,
      @RequestParam("remname") boolean remname,
      @RequestParam("autologin") boolean autologin,
      HttpServletRequest request,
      HttpServletResponse response) {
    try {
      String ticket = userService.loginUser(user, valistr, token);
      if (StringUtils.isEmpty(ticket)) {
        return SysResult.build(201, "用户不存在", null);
      } else {
        //        这里的EM_TICKET类似于JAVA-SESSIONID
        CookieUtils.setCookie(request, response, "EM_TICKET", ticket, -1, true);
        if (remname || autologin) {
          CookieUtils.setCookie(
              request, response, "USERNAME", user.getUserName(), Integer.MAX_VALUE, true);
        }
        if (autologin) {
          CookieUtils.setCookie(
              request, response, "PASSWORD", user.getUserPassword(), 2592000, true);
        }
        return SysResult.ok();
      }
    } catch (MsgException e) {
      return SysResult.build(201, e.getMessage(), e);
    } catch (Exception e) {
      e.printStackTrace();
      return SysResult.build(500, e.getMessage(), e);
    }
  }

  /**
   * 自动登录
   *
   * @param user
   * @param request
   * @param response
   * @return
   */
  @RequestMapping("/manage/autologin")
  @ResponseBody
  public SysResult autoLogin(User user, HttpServletRequest request, HttpServletResponse response) {
    try {
      String ticket = userService.loginUser(user);
      if (StringUtils.isEmpty(ticket)) {
        return SysResult.build(201, "时间间隙太短", null);
      } else {
        CookieUtils.setCookie(request, response, "EM_TICKET", ticket, -1, true);
        return SysResult.ok(user);
      }
    } catch (MsgException e) {
      return SysResult.build(201, e.getMessage(), e);
    } catch (Exception e) {
      return SysResult.build(500, e.getMessage(), e);
    }
  }

  /**
   * 获取用户登陆状态
   *
   * @param ticket
   * @param request
   * @param response
   * @return
   */
  @RequestMapping("/manage/query/{ticket}")
  @ResponseBody
  public SysResult loginStatus(
      @PathVariable("ticket") String ticket,
      HttpServletRequest request,
      HttpServletResponse response) {
    try {
      String user = userService.loginState(ticket);
      if (user == null) {
        //        如果没有登陆则删除cookie
        CookieUtils.deleteCookie(request, response, "EM_TICKET");
        CookieUtils.deleteCookie(request, response, "USERNAME");
        CookieUtils.deleteCookie(request, response, "PASSWORD");
        return SysResult.build(201, "尚未登陆", null);
      } else {
        return SysResult.ok(user);
      }
    } catch (Exception e) {
      return SysResult.build(500, e.getMessage(), e);
    }
  }

  /**
   * 用户登出
   *
   * @param ticket
   * @param request
   * @param response
   * @return
   */
  @RequestMapping("/manage/logout")
  @ResponseBody
  public SysResult logoutUser(
      @CookieValue("EM_TICKET") String ticket,
      HttpServletRequest request,
      HttpServletResponse response) {
    try {
      userService.deleteTicket(ticket);
      CookieUtils.deleteCookie(request, response, "EM_TICKET");
      CookieUtils.deleteCookie(request, response, "USERNAME");
      CookieUtils.deleteCookie(request, response, "PASSWORD");
      return SysResult.ok();
    } catch (Exception e) {
      return SysResult.build(500, e.getMessage(), e);
    }
  }

  /**
   * 查询用户的权限
   *
   * @param ticket 登录凭据
   * @return 空表示没查到，数字表示权限
   */
  @RequestMapping("/manage/userType")
  @ResponseBody
  public Integer queryUserType(@RequestParam("ticket") String ticket) {
    try {
      return userService.queryUserType(ticket);
    } catch (Exception e) {
      e.printStackTrace();
      return 0;
    }
  }
}
